package top.infopub.mgr.mkt.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.enums.mkt.StandardEnum;
import top.infopub.enums.sg.CoopInfoTypesEnums;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.ProTrackDomain;
import top.infopub.mgr.mkt.jsonvo.CollectJsonVo;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.service.CollectProjectService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.ProTrackService;
import top.infopub.mgr.mkt.vo.InvestmentInfoVo;
import top.infopub.mgr.mkt.vo.ItemNameVo;
import top.infopub.mgr.mkt.vo.ProTrackVo;
import top.infopub.mgr.mkt.vo.TrackVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.model.mkt.*;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
public class ProTrackServiceImpl extends GenericServiceImpl<ProTrack, String> implements ProTrackService {

    @Autowired
    private ProTrackDao proTrackDao;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private AfterSummaryCoopDao afterSummaryCoopDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;

    @Autowired
    private ProjectRiskDao projectRiskDao;

    @Autowired
    private BaseLineService baseLineService;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private CollectProjectService collectProjectService;

    @Autowired
    private ProProgressDao proProgressDao;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private CollectProjectDao collectProjectDao;

    @Override
    public GenericDao<ProTrack, String> getDao() {
        return proTrackDao;
    }

    @Autowired
    private TrackInfoDao trackInfoDao;

    @Override
    public Page<ProTrackDomain> selectByDomainWhere(Page<ProTrackDomain> page,
                                                    ProTrackVo proTrackVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProTrackDomain>)proTrackDao.selectByDomainWhere(proTrackVo);
    }

    @Override
    public Page<ProTrackDomain> selectDistinctByDomainWhere(Page<ProTrackDomain> page,
                                                    ProTrackVo proTrackVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProTrackDomain>)proTrackDao.selectDistinctByDomainWhere(proTrackVo);
    }


    @Override
    public Page<ProTrackDomain> selectMyCheckByDomainWhere(Page<ProTrackDomain> page,
                                                           ProTrackVo proTrackVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProTrackDomain>)proTrackDao.selectMyCheckByDomainWhere(proTrackVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProTrack(ProTrack proTrack) {
        //执行新增
        if (StringUtils.isEmpty(proTrack.getId())) {
            String generatorCode = codeGeneratorConfigService.generatorCode("mkt_pro_track");
//            proTrack.setCodes(generatorCode);
            AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
            String id = IdFactory.getUUIDUpper();
            // String processId = IdFactory.getUUIDUpper();
            proTrack.setId(id);
            proTrack.setAddBy(vo.getId());
            proTrack.setAddTime(DateUtils.getCurrentDateTime());
            // 处理processId
            // proTrack.setProcessId(processId);
            // proTrack.setProcessStatus("1");//审批中
//            proTrack.setUptBy(vo.getId());
//            proTrack.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            proTrackDao.insert(proTrack);

            // 注意 这里根据不同的业务分支判断条件 获得不同enum
            //  FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_PRO_TRACK;
            // 处理工作流数据
            //  wsFlowProcess.launch(templateEnum, proTrack.getId(), proTrack.getProcessId());
        }
    }

    @Override
    public ProTrackDomain selectDomainById(String id) {

        return proTrackDao.selectDomainById(id);
    }

    @Override
    public CollectJsonVo queryDetailById(String proCode) {
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        CollectJsonVo collectJsonVo = new CollectJsonVo();
        //基础信息
        ProTrack proTrack1 = proTrackDao.selectByProCode(proCode);
        ProjectInfo projectInfo = projectInfoDao.findTailByProCode(proCode);
        if (proTrack1!=null){
            projectInfo.setProcessId(proTrack1.getProcessId());
            projectInfo.setPreId(proTrack1.getId());
        }
        collectJsonVo.setProjectInfo(projectInfo);
        //项目合作单位信息
        collectJsonVo.setSummaryCoops(afterSummaryCoopDao.querySummaryCoopList(projectInfo.getProCode(), 0));
        //项目投资构成信息
        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(projectInfo.getProCode());
        if (projectSubInfo != null) {
            if (StringUtils.isNotBlank(projectSubInfo.getTitleJson())) {
                collectJsonVo.setItemName(JSON.parseArray(projectSubInfo.getTitleJson(), ItemNameVo.class));
            }
            if (StringUtils.isNotBlank(projectSubInfo.getContentJson())) {
                collectJsonVo.setInvestmentInfoVos(JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class));
            }
        }
        //如果是审批中则展示 全部风险
        //项目风险信息
        collectJsonVo.setRiskTable(projectRiskDao.selectByProCode(projectInfo.getProCode()));
        //底线标准情况
        collectJsonVo.setStandardTable(baseLineService.checkIsSatisfy(projectInfo.getProCode()));
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE2.getCode(), null);
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE43.getCode(), null);
        for (ProjectAttachment attachment : attachmentList) {
            projectAttaList.add(attachment);
        }
        collectJsonVo.setFileAtt(fileAttaListToArray(projectAttaList));
        //合作单位信息
        List<CoopInfo> coopInfoList = coopInfoService.queryByTypes(CoopInfoTypesEnums.OWNER, 1);
        collectJsonVo.setCoopInfoList(coopInfoList);

        //跟踪信息
        ProTrack proTrack = new ProTrack();
        ProProcessDetailTypeEnum proProcessDetailTypeEnum = proProcessManageService.queryProProcessType(proCode);
//        String proStage = proProcessManageService.queryProProcessType(proCode).getTypeName();
        proTrack.setProStage(proProcessDetailTypeEnum.getTypeName()); //阶段
        proTrack.setAddBy(userDtl.getRealName());
        proTrack.setAddTime(new Date());
        if ("1".equals(proProcessDetailTypeEnum.getType())){//跟踪阶段C 立项阶段B 资格预审阶段A
            proTrack.setProLevel("C");
        }else if("2".equals(proProcessDetailTypeEnum.getType())){
            proTrack.setProLevel("B");
        }else{
            proTrack.setProLevel("A");
        }
        collectJsonVo.setProTrack(proTrack);
        return collectJsonVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(ProjectInfo proInfo, List<AfterSummaryCoop> summCoopList, ProjectSubInfo proSubInfo, List<ProjectRisk> riskList, List<ProjectAttachment> attachmentList, List<ProProgress> proProgresses, ProTrack proTracks, AuthorizationVO userDtl,Integer submitType,String bodyStr,TrackInfo trackInfo) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(proInfo.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");

        //查询项目审核状态
        ProTrack proTrack2 = proTrackDao.selectByProCode(proInfo.getProCode());
        if (proTrack2!=null && StringUtils.isNotBlank(proTrack2.getProcessStatus())
                && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack2.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }
        proInfo.setId(tmpProInfo.getId());
        proInfo.setUptBy(userDtl.getId());
        proInfo.setUptTime(new Date());
        //更新项目基础信息
        projectInfoDao.modifyProjectInfoBySeletive(proInfo);

        //更新项目合作单位
        afterSummaryCoopDao.deleteByProCode(proInfo.getProCode());
        afterSummaryCoopDao.insertByBatch(summCoopList);

        //更新子项表格信息数据
        ProjectSubInfo psi = projectSubInfoDao.queryByProCode(proInfo.getProCode());
        if (psi == null) {
            proSubInfo.setAddBy(userDtl.getId());
            proSubInfo.setAddTime(new Date());
            projectSubInfoDao.insert(proSubInfo);
        } else {
            proSubInfo.setId(psi.getId());
            projectSubInfoDao.modifyById(proSubInfo);
        }
        //更新风险信息
        if (riskList != null && riskList.size() > 0) {
            projectRiskDao.deleteByProCode(proInfo.getProCode());
            projectRiskDao.insertBatch(riskList);
        }
        //更新项目最新进展信息
   if (proProgresses.size()>0){
        proProgressDao.deleteByProCode(proInfo.getProCode());
        for (ProProgress proProgress : proProgresses) {
            proProgress.setProCode(proInfo.getProCode());
            proProgress.setAddBy(userDtl.getId());
            proProgress.setAddTime(new Date());
        }
            proProgressDao.insertBatch(proProgresses);
  }
        //更新附件信息
        projectAttachmentDao.deleteByWhere(proInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE3.getCode(), null);
        projectAttachmentDao.deleteByWhere(proInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE43.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

         //查询跟踪信息是否存在
        ProTrack proTrack = new ProTrack();
        ProTrack proTrack1 = proTrackDao.selectByProCode(proInfo.getProCode());
        //获取当前阶段
        String node = proProcessManageService.queryProProcessType(proInfo.getProCode()).getNode();
        if (proTrack1==null){
            proTrack.setId(IdFactory.getUUIDUpper());
            proTrack.setTrackStatus(node);
            proTrack.setProCode(proInfo.getProCode());
            proTrack.setAddBy(userDtl.getId());
            proTrack.setAddTime(new Date());
            if (trackInfo.getTodayMemo()!=null){
                proTrack.setTodayMemo(trackInfo.getTodayMemo());
            }
            if (trackInfo.getTomorrowPlan()!=null){
                proTrack.setTomorrowPlan(trackInfo.getTomorrowPlan());
            }
            proTrackDao.insert(proTrack);
        }else {
            if (trackInfo.getTodayMemo()!=null||trackInfo.getTomorrowPlan()!=null){
                proTrack.setId(proTrack1.getId());
                proTrack.setTrackStatus(node);
                if (trackInfo.getTodayMemo()!=null){
                    proTrack.setTodayMemo(trackInfo.getTodayMemo());
                }
                if (trackInfo.getTomorrowPlan()!=null){
                    proTrack.setTodayMemo(trackInfo.getTomorrowPlan());
                }
                proTrack.setTrackDate(new Date());
                proTrackDao.updateByPrimaryKey(proTrack);
            }
        }
        //更新跟踪信息列表数据
        if (StringUtils.isNotEmpty(trackInfo.getTodayMemo()) || StringUtils.isNotEmpty(trackInfo.getTomorrowPlan())){
            TrackInfo trackInfo1 = new TrackInfo();
            BeanUtils.copyProperties(trackInfo,trackInfo1);
                    trackInfo.setId(IdFactory.getUUIDUpper());
                    trackInfo.setAddBy(userDtl.getId());
                    trackInfo.setProStage(node);
                    trackInfo.setAddTime(new Date());
                    trackInfo.setTrackId(proTrack.getId());
                    trackInfoDao.insert(trackInfo);
        }
        //查询项目收集pk id 发起跟踪流程
        if (submitType==2){ //提交发起审批
            String s = proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE18, bodyStr, proTrack.getId(), proInfo.getProCode(), userDtl);
            return RspVo.getSuccessResponse(s);
        }
        return RspVo.getSuccessResponse(400,"提交成功");
    }

    @Override
    public Page<ProTrackDomain> selectPageByDomainWhere(Page<ProTrackDomain> page, ProTrackVo proTrackVo) {
        return proTrackDao.selectPageByDomainWhere(proTrackVo);
    }

    @Override
    public ProTrack selectByProCode(String proCode) {
        return proTrackDao.selectByProCode(proCode);
    }

    @Override
    public Page<ProTrackDomain> selectByTrackPage(Page<ProTrackDomain> page, String proCode) {
        return proTrackDao.selectByTrackPage(proCode);
    }

    @Override
    public Page<ProTrackDomain> selectByTrackVo(Page<ProTrackDomain> page, TrackVo trackVo) {

        return proTrackDao.selectByTrackVo(trackVo);
    }

    @Override
    public RspVo queryDetail(String proCode) {
       ProjectInfo projectInfo = proTrackDao.queryDetail(proCode);
       //获取建安工程费用
        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(proCode);
        List<InvestmentInfoVo> investmentInfoVos = JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class);
        BigDecimal rowSum = BigDecimal.ZERO;
        for (InvestmentInfoVo investmentInfoVo : investmentInfoVos) {
            if (StandardEnum.GET_JIANAN.getBaseLineName().equals(investmentInfoVo.getName())
            ){
                rowSum = investmentInfoVo.getTotal();
            }
        }
        projectInfo.setSumCae(rowSum);
        return RspVo.getSuccessResponse(projectInfo);
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
}
